package cn.wolfcode.trip.app.filter;

import cn.wolfcode.trip.base.util.UploadUtil;
import org.apache.commons.io.FileUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

public class ImageFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取当前请求的图片路径
        HttpServletRequest req = (HttpServletRequest) request;
        String imgURI = req.getRequestURI();
        //先查找当前项目的upload中是否存在该文件
        String path = request.getServletContext().getRealPath("/");
        File file = new File(path, imgURI);
        if (!file.exists()) {
            //如果不存在,就去公共图片文件夹拷贝到当前项目的upload,才放行
            File srcFile = new File(UploadUtil.COMMON_PATH, imgURI);
            FileUtils.copyFile(srcFile, file);
        }
        //如果存在就直接放行
        chain.doFilter(request, response);
    }

    public void destroy() {

    }
}
